package com.ruoyi.system.api.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.api.ResponseWithData;
import com.ruoyi.system.api.domain.ReportInfo;
import com.ruoyi.system.api.domain.StErrorReport;
import com.ruoyi.system.api.domain.StReportPort;
import com.ruoyi.system.api.mapper.PlanDetailsMapper;
import com.ruoyi.system.api.mapper.ReportInfoMapper;
import com.ruoyi.system.api.mapper.StReportPortMapper;
import com.ruoyi.system.api.service.CcService;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.api.mapper.StHotAccountReportMapper;
import com.ruoyi.system.api.domain.StHotAccountReport;
import com.ruoyi.system.api.service.IStHotAccountReportService;
import com.ruoyi.common.core.text.Convert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ObjectUtils;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2020-03-06
 */
@Service
public class StHotAccountReportServiceImpl implements IStHotAccountReportService {
    private static final Logger log = LoggerFactory.getLogger(StHotAccountReportServiceImpl.class);

    @Autowired
    private StHotAccountReportMapper stHotAccountReportMapper;

    /**
     * 工程师FSE计划详情表
     */
    @Autowired
    private PlanDetailsMapper planDetailsMapper;

    /**
     * 服务通知的子表服务表与报告关联表
     */
    @Autowired
    private ReportInfoMapper reportInfoMapper;

    /**
     * 报告与备件的关系表
     */
    @Autowired
    private StReportPortMapper reportPortMapper;

    /**
     * 调用CC接口service
     */
    @Autowired
    private CcService ccService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public StHotAccountReport selectStHotAccountReportById(Long id) {
        return stHotAccountReportMapper.selectStHotAccountReportById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param stHotAccountReport 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<StHotAccountReport> selectStHotAccountReportList(StHotAccountReport stHotAccountReport) {
        return stHotAccountReportMapper.selectStHotAccountReportList(stHotAccountReport);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param stHotAccountReport 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertStHotAccountReport(StHotAccountReport stHotAccountReport) {
        stHotAccountReport.setCreateTime(DateUtils.getNowDate());
        return stHotAccountReportMapper.insertStHotAccountReport(stHotAccountReport);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param stHotAccountReport 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateStHotAccountReport(StHotAccountReport stHotAccountReport) {
        stHotAccountReport.setUpdateTime(DateUtils.getNowDate());
        return stHotAccountReportMapper.updateStHotAccountReport(stHotAccountReport);
    }

    /**
     * 删除【请填写功能名称】对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteStHotAccountReportByIds(String ids) {
        return stHotAccountReportMapper.deleteStHotAccountReportByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteStHotAccountReportById(Long id) {
        return stHotAccountReportMapper.deleteStHotAccountReportById(id);
    }

    /**
     * 添加 Hot Account Report
     *
     * @param hotAccountReport
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/7 1:38 下午
     */
    @Override
    public ResponseWithData<?> addHoatAccountReport(StHotAccountReport hotAccountReport) {
        if (hotAccountReport.getPlanId() == null) {
            return new ResponseWithData<>().error("planId cannot be empty！");
        }
        if (hotAccountReport.getNoticeId() == null) {
            return new ResponseWithData<>().error("noticeId cannot be empty！");
        }
        if (hotAccountReport.getEnginnerId() == null) {
            return new ResponseWithData<>().error("enginnerId cannot be empty！");
        }
        if (StringUtils.isEmpty(hotAccountReport.getServiceNo())) {
            return new ResponseWithData<>().error("serviceNo cannot be empty！");
        }
        if (null == hotAccountReport.getHotAccountType()) {
            return new ResponseWithData<>().error("hotAccountType cannot be empty！");
        }
        if (null == hotAccountReport.getFailType()) {
            return new ResponseWithData<>().error("failType cannot be empty！");
        }
        if (StringUtils.isEmpty(hotAccountReport.getSeverityLevel())) {
            return new ResponseWithData<>().error("severityLevel cannot be empty！");
        }
        if (null == hotAccountReport.getInstrunmentStatus()) {
            return new ResponseWithData<>().error("instrunmentStatus cannot be empty！");
        }
        if (StringUtils.isEmpty(hotAccountReport.getProblem())) {
            return new ResponseWithData<>().error("problem cannot be empty！");
        }
        if (StringUtils.isEmpty(hotAccountReport.getWorkDone())) {
            return new ResponseWithData<>().error("workDone cannot be empty！");
        }

        // 1、保存Hot Account Report信息
        if (hotAccountReport.getId() == null) {
            hotAccountReport.setCreateTime(new Date());
            hotAccountReport.setCreateBy(hotAccountReport.getEnginnerId() + "");
            hotAccountReport.setDelFlag("0");
            hotAccountReport.setSyncFlag("0");
            stHotAccountReportMapper.insertStHotAccountReport(hotAccountReport);

            // Hot Account Report信息保存到主表 st_report_info
            ReportInfo reportInfo = new ReportInfo();
            reportInfo.setServiceNo(hotAccountReport.getServiceNo());
            reportInfo.setEnginnerId(hotAccountReport.getEnginnerId());
            reportInfo.setPlanId(hotAccountReport.getPlanId());
            reportInfo.setRelServiceNo(3L);
            reportInfo.setRelPlanId("st_hot_account_report");
            reportInfo.setBatchType(hotAccountReport.getId());
            reportInfo.setDelFlag("0");
            reportInfo.setCreateTime(new Date());
            reportInfo.setCreateBy(hotAccountReport.getEnginnerId() + "");
            reportInfo.setNoticeId(hotAccountReport.getNoticeId());
            reportInfo.setSyncFlag("0");
            reportInfo.setFseName(hotAccountReport.getFseName());
            // TODO 报告编号生成规则是什么
            reportInfoMapper.insertStReportInfo(reportInfo);
        } else {
            hotAccountReport.setUpdateTime(new Date());
            hotAccountReport.setUpdateBy(hotAccountReport.getEnginnerId() + "");
            stHotAccountReportMapper.updateStHotAccountReport(hotAccountReport);
            ReportInfo reportInfo = reportInfoMapper.selectStReportInfoByBatchType(hotAccountReport.getId(), "3");
            reportInfo.setUpdateBy(hotAccountReport.getEnginnerId() + "");
            reportInfo.setUpdateTime(new Date());
            reportInfo.setEnginnerId(hotAccountReport.getEnginnerId());
            reportInfo.setFseName(hotAccountReport.getFseName());
            reportInfoMapper.updateStReportInfo(reportInfo);
        }


        // 2、更新备件关联信息
        reportPortMapper.updatePhoneReportPortByHelpIdAndServiceNo(hotAccountReport.getId(), hotAccountReport.getHelpId(), hotAccountReport.getServiceNo());


        return new ResponseWithData<>().success(hotAccountReport).code(200);
    }

    /**
     * 修改 Hot Account Report
     *
     * @param hotAccountReport
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/7 1:39 下午
     */
    @Override
    public ResponseWithData<?> updateHoatAccountReport(StHotAccountReport hotAccountReport) {
        if (hotAccountReport.getId() == null) {
            return new ResponseWithData<>().error("id cannot be empty！");
        }
        if (hotAccountReport.getPlanId() == null) {
            return new ResponseWithData<>().error("planId cannot be empty！");
        }
        if (hotAccountReport.getNoticeId() == null) {
            return new ResponseWithData<>().error("noticeId cannot be empty！");
        }
        if (hotAccountReport.getEnginnerId() == null) {
            return new ResponseWithData<>().error("enginnerId cannot be empty！");
        }
        if (StringUtils.isEmpty(hotAccountReport.getServiceNo())) {
            return new ResponseWithData<>().error("serviceNo cannot be empty！");
        }
        if (null == hotAccountReport.getHotAccountType()) {
            return new ResponseWithData<>().error("hotAccountType cannot be empty！");
        }
        if (null == hotAccountReport.getFailType()) {
            return new ResponseWithData<>().error("failType cannot be empty！");
        }
        if (StringUtils.isEmpty(hotAccountReport.getSeverityLevel())) {
            return new ResponseWithData<>().error("severityLevel cannot be empty！");
        }
        if (null == hotAccountReport.getInstrunmentStatus()) {
            return new ResponseWithData<>().error("instrunmentStatus cannot be empty！");
        }
        if (StringUtils.isEmpty(hotAccountReport.getProblem())) {
            return new ResponseWithData<>().error("problem cannot be empty！");
        }
        if (StringUtils.isEmpty(hotAccountReport.getWorkDone())) {
            return new ResponseWithData<>().error("workDone cannot be empty！");
        }

        // 1、保存Hot Account Report信息
        hotAccountReport.setUpdateTime(new Date());
        hotAccountReport.setUpdateBy(hotAccountReport.getEnginnerId() + "");
        stHotAccountReportMapper.updateStHotAccountReport(hotAccountReport);

        ReportInfo reportInfo = reportInfoMapper.selectStReportInfoByBatchType(hotAccountReport.getId(), "3");
        reportInfo.setUpdateBy(hotAccountReport.getEnginnerId() + "");
        reportInfo.setUpdateTime(new Date());
        reportInfo.setEnginnerId(hotAccountReport.getEnginnerId());
        reportInfo.setFseName(hotAccountReport.getFseName());
        reportInfoMapper.updateStReportInfo(reportInfo);

        // 2、更新备件关联信息
        reportPortMapper.updatePhoneReportPortByHelpIdAndServiceNo(hotAccountReport.getId(), hotAccountReport.getHelpId(), hotAccountReport.getServiceNo());

        return new ResponseWithData<>().success(hotAccountReport).code(200);
    }

    /**
     * 提交 Hot Account Report
     *
     * @param id
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/7 1:39 下午
     */
    @Override
    public ResponseWithData<?> hoatAccountReportSubmit(Long id, Long enginnerId) {
        if (null == id) {
            return new ResponseWithData<>().error().msg("id cannot be empty");
        }
        if (null == enginnerId) {
            return new ResponseWithData<>().error().msg("enginnerId cannot be empty");
        }
        // 查寻电话解决报告基本信息
        StHotAccountReport stHotAccountReport = stHotAccountReportMapper.selectStHotAccountReportById(id);
        ReportInfo reportInfo = reportInfoMapper.selectStReportInfoByBatchType(id, "3");
        if (null == stHotAccountReport || null == reportInfo) {
            return new ResponseWithData<>().error().msg("Hot Account Report不存在");
        }
        if ("1".equals(reportInfo.getSyncFlag())) {
            return new ResponseWithData<>().error().msg("此Hot Account Report已提交过");
        }

        Map<String, String> params = new HashMap<>();
        // 唯一主键
        params.put("report_guid", reportInfo.getId().toString());
        // Service号
        params.put("service_no", reportInfo.getServiceNo());
        // 提交的工程师ID
        params.put("enginner_id", enginnerId + "");
        // 安装日期
        params.put("install_date", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stHotAccountReport.getInstallDate()));
        // sales
        params.put("sales", stHotAccountReport.getSales());
        // hot_account_type
        params.put("hot_account_type", stHotAccountReport.getHotAccountType());
        // fail_type
        params.put("fail_type", stHotAccountReport.getFailType());
        // instrunment_status
        params.put("instrunment_status", stHotAccountReport.getInstrunmentStatus());
        // 开始时间
        params.put("start_date", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stHotAccountReport.getStartDate()));
        // 结束时间
        params.put("end_date", DateUtils.parseDateToStrEmpty(DateUtils.YYYY_MM_DD_HH_MM_SS, stHotAccountReport.getEndDate()));
        // 问题原因
        params.put("problem", stHotAccountReport.getProblem());
        // work_done
        params.put("work_done", stHotAccountReport.getWorkDone());
        // 设备模块
        params.put("equipment_mode", StringUtils.isEmpty(stHotAccountReport.getEquipmentMode()) ? "" : stHotAccountReport.getEquipmentMode());
        // 设备序列号
        params.put("serial_no", stHotAccountReport.getSerialNo());
        // Severitylevel
        params.put("Severity_level", stHotAccountReport.getSeverityLevel());
        // 备件信息
        List<StReportPort> stReportPorts = reportPortMapper.selectStReportPortListByReportIdAndPortType(stHotAccountReport.getId(), "4");
//获取已提交的报告备件
        List<StReportPort> reportPortsSubmited = reportPortMapper.getSubmitServiceAndPhoneReportPorts(stHotAccountReport.getServiceNo());
        if (null != stReportPorts) {
            if (null != reportPortsSubmited) {
                stReportPorts.addAll(reportPortsSubmited);
            }
        } else {
            stReportPorts = reportPortsSubmited;
        }
        if (StringUtils.isNotEmpty(stReportPorts)) {
            List<Map<String, Object>> reportPortParams = new ArrayList<>();
            for (StReportPort stReportPort : stReportPorts) {
                Map<String, Object> reportPortParam = new HashMap<>();
                // 备件号
                reportPortParam.put("part_number", stReportPort.getPartNumber());
                // 借贷单号
                reportPortParam.put("loan_number", StringUtils.isEmpty(stReportPort.getLoanNumber()) ? "" : stReportPort.getLoanNumber());
                // 备件序列号
                reportPortParam.put("part_serial_number", stReportPort.getPartNumber());
                // 备件名称
                reportPortParam.put("part_name", stReportPort.getPartName());
                //	QTY数量
                reportPortParam.put("qty_count", stReportPort.getQtyCount());
                // Price单价
                reportPortParam.put("price", stReportPort.getPrice());
                // Price总价
                reportPortParam.put("totalprice", stReportPort.getTotalprice());
                // 更换类型

                if (StringUtils.isNotEmpty(stReportPort.getPartType())) {
                    reportPortParam.put("part_type", stReportPort.getPartType());
                } else {
                    reportPortParam.put("part_type", "");
                }
                // 备注
                reportPortParam.put("remark", StringUtils.isEmpty(stReportPort.getRemark()) ? "" : stReportPort.getRemark());
                // 备件收货地址
                reportPortParam.put("Address", StringUtils.isEmpty(stReportPort.getAddress()) ? "" : stReportPort.getAddress());
                reportPortParams.add(reportPortParam);
            }
            params.put("part_data", JSON.toJSONString(reportPortParams));
        } else {
            params.put("part_data", "[]");
        }

        // 请求CC接口 提交电话解决报告
        String response = ccService.accountReporthandle(params);

        /** 如果调用接口异常直接返回 */
        if (null == response) {
            return new ResponseWithData().error().msg("提交Hot Account Report失败 调用CC端提交Hot Account Report接口发生异常").code(202);
        }

        JSONObject jsonObject = JSONObject.parseObject(response);
        String status = jsonObject.getString("status");
        if ("1".equals(status)) {

            String rptNo = "";
            try {
                JSONArray record = jsonObject.getJSONArray("record");
                if (record != null && record.size() > 0) {
                    rptNo = record.getJSONObject(0).getString("rpt_no");
                }
            } catch (Exception e) {
                log.error("程序异常", e.getMessage());
            }
            // 提交成功 ，更新同步状态
            ReportInfo info = new ReportInfo();
            info.setId(reportInfo.getId());
            info.setSyncFlag("1");
            info.setSyncTime(new Date());
            info.setReportNo(rptNo);
            reportInfoMapper.updateStReportInfo(info);

            return new ResponseWithData().success().msg("提交Hot Account Report成功").code(200);
        } else if ("2".equals(status)) {
            String message = jsonObject.getString("message");
            return new ResponseWithData().error().msg(message).code(201);
        } else {
            return new ResponseWithData().error().msg("提交Hot Account Report失败 调用CC端提交Hot Account Report接口发生异常").code(201);
        }
    }

    /**
     * 查看 Hot Account Report
     *
     * @param id
     * @return com.ruoyi.system.api.ResponseWithData<?>
     * @author yzg
     * @date 2020/3/7 1:40 下午
     */
    @Override
    public ResponseWithData<?> detailHoatAccountReport(Long id) {
        StHotAccountReport stHotAccountReport = stHotAccountReportMapper.selectStHotAccountReportById(id);
        if (stHotAccountReport != null) {
            ReportInfo reportInfo = reportInfoMapper.selectStReportInfoByBatchType(stHotAccountReport.getId(), "3");
            stHotAccountReport.setPlanId(reportInfo.getPlanId());
            stHotAccountReport.setNoticeId(reportInfo.getNoticeId());
        }
        return new ResponseWithData<>().success(stHotAccountReport).code(200);
    }

    @Override
    public List<ReportInfo> selectStHotAccountReportList(String serviceNo, Long enginnerId) throws Exception {
        return reportInfoMapper.selectStReportInfoByServiceNoAndRelServiceNo(serviceNo, "3");
    }

    @Override
    public ResponseWithData<?> delHotAccountReport(Long id, Long enginnerId) throws Exception {
        ReportInfo reportInfo = reportInfoMapper.selectStReportInfoById(id);
        if (null == reportInfo) {
            return new ResponseWithData<>().error().code(201).msg("报告不存在");
        }
        String syncFlag = reportInfo.getSyncFlag();
        if ("1".equals(syncFlag)) {
            String response = ccService.deleteServiceReport(enginnerId, reportInfo.getServiceNo(), reportInfo.getId() + "");

            /** 如果调用接口异常直接返回 */
            if (null == response) {
                return new ResponseWithData().error().msg("删除服务报告失败 调用CC端删除服务报告接口发生异常").code(202);
            }

            JSONObject jsonObject = JSONObject.parseObject(response);
            String status = jsonObject.getString("status");
            if ("1".equals(status)) {

                reportInfo.setUpdateTime(new Date());
                reportInfo.setUpdateBy(enginnerId + "");
                reportInfo.setDelFlag("2");
                reportInfoMapper.updateStReportInfo(reportInfo);

                return new ResponseWithData<>().success().code(200).msg("删除成功");
            } else if ("2".equals(status)) {
                String message = jsonObject.getString("message");
                return new ResponseWithData().error().msg(message).code(201);
            } else {
                return new ResponseWithData().error().msg("删除服务报告失败 调用CC端删除服务报告接口发生异常常").code(201);
            }
        } else {
            reportInfo.setUpdateTime(new Date());
            reportInfo.setUpdateBy(enginnerId + "");
            reportInfo.setDelFlag("2");
            reportInfoMapper.updateStReportInfo(reportInfo);
            return new ResponseWithData<>().success().code(200).msg("删除成功");
        }
    }

    @Override
    public List<ReportInfo> selectStHotAccountReportList(ReportInfo reportInfo) {
        return reportInfoMapper.selectStReportInfoList(reportInfo);
    }


    @Override
    public ResponseWithData<?> getStHotAccountReportList(Map map) {
        JSONObject jSONObject = ccService.getStHotAccountReportList(map);
        /** 如果调用接口异常直接返回 */
        if (null == jSONObject) {
            return new ResponseWithData().error().msg("提交Hot Account Report失败 调用CC端提交Hot Account Report接口发生异常").code(202);
        }
        JSONArray jsonArray = jSONObject.getJSONArray("record");
        if (!ObjectUtils.isEmpty(jsonArray)) {
            for (Object object : jsonArray) {
                JSONObject jsonObj = (JSONObject) object;
                String date1 = jsonObj.getString("Date1");
                String date2 = jsonObj.getString("Date2");
                if (StringUtils.isNotEmpty(date1)) {
                    DateTimeFormatter df = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss.SSS");
                    String datee1 = df.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.valueOf(date1.substring(date1.indexOf("(") + 1, date1.indexOf("+")))), ZoneId.of("Asia/Shanghai")));
                    jsonObj.put("date1", datee1.substring(0, 10));
                }
                if (StringUtils.isNotEmpty(date2)) {
                    DateTimeFormatter df = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss.SSS");
                    String datee2 = df.format(LocalDateTime.ofInstant(Instant.ofEpochMilli(Long.valueOf(date2.substring(date2.indexOf("(") + 1, date2.indexOf("+")))), ZoneId.of("Asia/Shanghai")));
                    jsonObj.put("date2", datee2.substring(0, 10));
                }
                String partData = jsonObj.getString("Part_data");
                JSONArray json = JSONArray.parseArray(partData);
                jsonObj.put("Part_data", json);
            }
        }
        return new ResponseWithData<>().success(jSONObject).code(200);
    }
}
